package com.security.door.comm;

import com.alibaba.fastjson.JSON;
import com.security.door.model.vo.treeViewVo;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: admin
 * @description:
 * @author: Mr.Chen
 * @create: 2018-05-03 17:43
 **/
public class TreeBuilder {
    List<treeViewVo> nodes = new ArrayList<>();

    public String buildTree(List<treeViewVo> nodes) {
        TreeBuilder treeBuilder = new TreeBuilder(nodes);
        return treeBuilder.buildJSONTree();
    }

    public TreeBuilder() {
    }

    public TreeBuilder(List<treeViewVo> nodes) {
        super();
        this.nodes = nodes;
    }

    // 构建JSON树形结构
    public String buildJSONTree() {
        List<treeViewVo> nodeTree = buildTree();
        return JSON.toJSONString(nodeTree);
    }

    // 构建树形结构
    public List<treeViewVo> buildTree() {
        List<treeViewVo> treeNodes = new ArrayList<>();
        List<treeViewVo> rootNodes = getRootNodes();
        for (treeViewVo rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    // 递归子节点
    public void buildChildNodes(treeViewVo node) {
        List<treeViewVo> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (treeViewVo child : children) {
                buildChildNodes(child);
            }
            node.setNodes(children);
        }
    }

    // 获取父节点下所有的子节点
    public List<treeViewVo> getChildNodes(treeViewVo pnode) {
        List<treeViewVo> childNodes = new ArrayList<>();
        for (treeViewVo n : nodes) {
            if (pnode.getId() == (n.getParentid())) {
                childNodes.add(n);
            }
        }
        return childNodes;
    }

    // 判断是否为根节点
    public boolean rootNode(treeViewVo node) {
        boolean isRootNode = true;
        for (treeViewVo n : nodes) {
            if (node.getParentid() == n.getId()) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }
    // 获取集合中所有的根节点
    public List<treeViewVo> getRootNodes() {
        List<treeViewVo> rootNodes = new ArrayList<>();
        for (treeViewVo n : nodes) {
            if (rootNode(n)) {
                rootNodes.add(n);
            }
        }
        return rootNodes;
    }
}
